package com.itheima.Filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * <p>Description: 检查用户是否已经完成登录</p>
 *
 * @author liuyiming
 * @date 2022-10-06 16:58
 * @version 1.0.0
 */
@Slf4j
//java Servlet中的注解      /*：表示拦截所有
@WebFilter(filterName = "LoginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    //定义不需要处理的请求路径
    //  **：匹配多个目录       *：匹配单个目录        ?：匹配单个字符
    public static final List<String> urls = Arrays.asList(
            "/employee/login",
            "employee/logout",
            "/backend/**",
            "/front/**",
            "/common/**",       //上传下载
            "/user/sendMsg",    //移动端发送短信
            "/user/login"       //移动端用户登录
    );

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1. 获取本次请求的URI
        /*
            路径：127.0.0.1:8080/backend/login.html
                url: 127.0.0.1:8080/backend/login.html
                URI: backend/login.html
        */
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);

        //2. 判断本次请求是否需要处理
        boolean check = check(requestURI);

        //3.如果不需要处理，则直接放行
        if(check){
            log.info("本次请求{}不需要进行处理",requestURI);
            filterChain.doFilter(request, response);
            return;
        }

        //4-1.判断管理员登录状态，如果已经登录，则直接放行
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null){
            log.info("用户{}已登录",empId);
            /*
            * 调用BaseContext中的ThreadLocal工具，在线程中开辟一处空间存入id，当前id只在当前线程中有效
            * 因为填充公共字段类中不能获取session，也就不能通过session获取id
            * 并且当前类是一个线程中最先执行的
            * 所以就可以在当前类中存入id，填充公共字段类就可以通过ThreadLocal来获取当前登录用户id
            * */
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }

        //4-2.判断用户登录状态，如果已经登录，则直接放行
        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null){
            log.info("用户{}已登录",userId);
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }

        log.info("管理员用户未登录");
        //5.如果未登录则直接返回未登录信息，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * <p>Description: 路径匹配，检查本次请求是否需要放行</p>
     *
     * @author liuyiming
     * @date 2022-10-06 18:40
     * @version 1.0.0
     */
    private boolean check(String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
